import React, { useMemo, useState } from 'react'
import { CancelIcon, PopIcon, StyledPopWrap, StyledWrap } from './style'
import LabelWrap from '../../components/LabelWrap'
import { CheckBox, Input, InputNumber, Radio, RadioGroup, Select, Switch, Trigger } from '@kedacom/react-next'
import { useMeetingParamsStore } from './store'
import shallow from 'zustand/shallow'
import { useBasicInfoStore } from '../basicInfo/store'
import Alert from '@/components/Alert'
import { getRule } from '../../rules'
import { useCreateContentStore } from '../../store'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import MedialAbility from './MedialAbility'
import CreateMember from '../../components/CreateMember'
import { setKcList } from '../../store.combine'
import { t } from 'i18next'
import { changeEncryptionType, changeMeetingType, changeRtc, changeVoiceInspireEnable } from './store.combine'
import { useUserAllStore } from '../user/all/store'
import { changeCascadeInUser } from '../user/store.combine'
import { useGlobalStore } from '@/store/global'
import { checkPermission, isMeetingCore } from '@/utils'
import { meetingTypeChangeListener } from '../vmp/store.combine'

export default function MeetingParams() {
	const [typeModalOpen, setTypeModalOpen] = useState(false)
	const [protocolModalOpen, setProtocolModalOpen] = useState(false)

	const { update, ...state } = useMeetingParamsStore((state) => ({ ...state }), shallow)

	const permission = useCreateContentStore((state) => state.permission)
	const _container = useCreateContentStore((state) => state._container, shallow)
	const superMtNum = useBasicInfoStore((state) => state.superMtNum)
	const SWITCH = useGlobalStore((state) => state.SWITCH)

	const isShowRtc = useMemo(() => {
		return (
			(state.meetingType === 0 && permission.tradMix !== 0) ||
			(state.meetingType === 1 && permission.portMix !== 0)
		)
	}, [state.meetingType, permission])

	const encryptionTypeSourceList = useMemo(() => {
		if (state.meetingType === 2) {
			return [checkPermission('10', SWITCH.create.encryptionType) && { label: t('AES加密'), value: 2 }].filter(
				Boolean
			) as { label: string; value: number }[]
		} else {
			return [
				{ label: t('不加密'), value: 0 },
				checkPermission('10', SWITCH.create.encryptionType) && { label: t('AES加密'), value: 2 },
				!state.enableRtc &&
					permission.certificate &&
					checkPermission('01', SWITCH.create.encryptionType) && { label: t('国密加密'), value: 3 },
			].filter(Boolean) as { label: string; value: number }[]
		}
	}, [state.meetingType, state.enableRtc, permission.certificate])

	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication({ onlyDialog: true })

	const meetingTypePanel = (
		<StyledPopWrap>
			<div className="pop-title">
				{t('会议类型注释')}
				<CancelIcon
					onClick={() => {
						setTypeModalOpen(false)
					}}
				/>
			</div>
			<div className="pop-content">
				{state._meetingTypeList.find((item) => item.value === 0) && (
					<>
						<strong>{t('传统会议')}</strong>
						<div className="pop-paragraph">
							{SWITCH.create.rtc && permission.tradMix !== 0
								? t(
										'支持RTC、SIP、H.323协议的会议终端接入、电话接入；多路音视频格式可适配；具备轻量超元RTC会议的优点。'
								  )
								: t('支持SIP、H.323协议的会议终端接入、电话接入；多路音视频格式可适配。')}
						</div>
					</>
				)}
				{state._meetingTypeList.find((item) => item.value === 1) && (
					<>
						<strong>{t('端口会议')}</strong>
						<div className="pop-paragraph">
							{SWITCH.create.rtc && permission.portMix !== 0
								? t(
										'支持RTC、SIP、H.323协议的会议终端接入、电话接入；为每个与会终端单独分配适配资源，实现任意视频格式、不同带宽的终端接入，获得更高质量视频体验；兼具全编全解端口会议和轻量超元RTC会议的优点。'
								  )
								: t(
										'支持SIP、H.323协议的会议终端接入、电话接入；为每个与会终端单独分配适配资源，实现任意视频格式、不同带宽的终端接入，获得更高质量视频体验。'
								  )}
						</div>
					</>
				)}
				{state._meetingTypeList.find((item) => item.value === 2) && (
					<>
						<strong>{t('超元RTC会议')}</strong>
						<div className="pop-paragraph">
							{t(
								'支持RTC协议的会议终端接入；MCU转发多路视频流，与会终端可自主进行多画面的布局，资源占用小、会议容量大、网络延迟低，极致视频会议体验。'
							)}
						</div>
					</>
				)}
			</div>
		</StyledPopWrap>
	)

	const protocolPanel = (
		<StyledPopWrap>
			<div className="pop-title">
				{t('优选呼叫协议注释')}
				<CancelIcon onClick={() => setProtocolModalOpen(false)} />
			</div>
			<div className="pop-content">
				{SWITCH.create.rtc ? (
					<>
						<p>{t('优选RTC时，呼叫顺序为RTC→SIP→H.323')}</p>
						<p>{t('优选SIP时，呼叫顺序为SIP→RTC→H.323')}</p>
						<p>{t('优选H.323时，呼叫顺序为H.323→RTC→SIP')}</p>
					</>
				) : (
					<>
						<p>{t('优选SIP时，呼叫顺序为SIP→H.323')}</p>
						<p>{t('优选H.323时，呼叫顺序为H.323→SIP')}</p>
					</>
				)}
			</div>
		</StyledPopWrap>
	)

	const isSfu = useMemo(() => state.meetingType === 2, [state.meetingType])

	/**当传统会议勾选h265和4K60后，原资源预占相关按钮置灰不可修改 */
	const isSourceUsedDisabled = useMemo(
		() => state.meetingType === 0 && state.frame === 60 && state.resolution === 16,
		[state.meetingType, state.frame, state.resolution]
	)

	return (
		<StyledWrap>
			<LabelWrap
				show={!!SWITCH.showMeetingType}
				label={t('会议类型')}
				tips={
					<Trigger
						container={() => _container}
						popup={meetingTypePanel}
						popupPlacement="bottomStart"
						open={typeModalOpen}
						onClick={() => setTypeModalOpen(!typeModalOpen)}
					>
						<PopIcon className={`type-pop_icon ${typeModalOpen ? 'active' : ''}`} />
					</Trigger>
				}
			>
				{state._meetingTypeList.length > 1 ? (
					<RadioGroup
						className="row-radio"
						options={state._meetingTypeList.map((item) => ({ ...item, width: 122 }))}
						value={state.meetingType}
						onChange={(e, v) => {
							meetingTypeChangeListener(state.meetingType, v)
							changeMeetingType(v)
						}}
					/>
				) : (
					<div>{state._meetingTypeList[0]?.label}</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('允许RTC接入')} show={isShowRtc && SWITCH.create.rtc}>
				<Switch
					width={40}
					height={22}
					checked={state.enableRtc}
					onChange={(e, v) => {
						changeRtc(v)
					}}
				/>
			</LabelWrap>
			<LabelWrap
				label={t('优选呼叫协议')}
				show={!isSfu}
				tips={
					<Trigger
						container={() => _container}
						popup={protocolPanel}
						popupPlacement="bottomStart"
						open={protocolModalOpen}
						onClick={() => setProtocolModalOpen(!protocolModalOpen)}
					>
						<PopIcon className={`protocol_pop_icon ${protocolModalOpen ? 'active' : ''}`} />
					</Trigger>
				}
			>
				<Select
					container={() => _container}
					width={200}
					options={
						state.enableRtc && !state._H265 && state.encryptionType !== 3 && !!SWITCH.create.rtc
							? [
									{ label: 'H323', value: 0 },
									{ label: 'SIP', value: 1 },
									{ label: 'RTC', value: 2 },
							  ]
							: [
									{ label: 'H323', value: 0 },
									{ label: 'SIP', value: 1 },
							  ]
					}
					value={state.meetingProtocol}
					onChange={(e, v) => {
						update({ meetingProtocol: v })
					}}
				/>
			</LabelWrap>
			<LabelWrap
				label={t('媒体资源')}
				show={state.meetingType === 0 && permission.integrated}
				className="mediaReaource"
			>
				<RadioGroup
					direction="column"
					value={state.sourceUsed}
					disabled={isSourceUsedDisabled}
					onChange={(e, v) => {
						if (v === 2) {
							if (state.enableRtc && permission.tradMix !== 0) {
								Alert(t('传统会议纯转发会议不支持RTC接入'))
								return
							}
						}
						if (useBasicInfoStore.getState().superMtNum) {
							Alert(t('传统会议纯转发会议不支持超大方。'))
							return
						}
						update({ sourceUsed: v })
					}}
				>
					<Radio value={2} className="first-radio-item">
						{t('纯转发会议')}
						<span className="tip">{t('不占用媒体资源')}</span>
					</Radio>
					<Radio value={1}>
						{t('资源预占')}
						<span className="tip last">{t('会议始终占用媒体资源直至会议结束')}</span>
					</Radio>
				</RadioGroup>
			</LabelWrap>
			{/* 媒体能力 */}
			<LabelWrap label={t('媒体能力')} className="media-ability-line">
				<MedialAbility />
			</LabelWrap>
			<LabelWrap label={t('级联会议')} className="cascade-line" show={!isSfu}>
				{superMtNum ? (
					<span>{t('简单级联')}</span>
				) : (
					<>
						<RadioGroup
							value={state.simpleCascade}
							direction="column"
							options={
								isMeetingCore()
									? [
											{ label: t('智能级联'), value: 2, className: 'first-radio-item' },
											{ label: t('简单级联'), value: 0, className: 'first-radio-item' },
											{ label: t('合并级联'), value: 1 },
									  ]
									: [
											{ label: t('简单级联'), value: 0, className: 'first-radio-item' },
											{ label: t('合并级联'), value: 1 },
									  ]
							}
							onChange={(e, v) => {
								const isTemplate = useCreateContentStore.getState().isTemplate
								if (v === 2) {
									const tree = useUserAllStore.getState().tree
									let flag = tree.some((item) => item.mcc.account_type === 10)
									if (flag) {
										Alert(t('智能级联不支持级联模板。'))
										return
									}
									if (isTemplate) {
										useBasicInfoStore.setState({
											preAssignedMeetingCheck: true,
										})
									}
								} else {
									changeCascadeInUser(v === 0 ? false : true)
								}

								update({ simpleCascade: v })
							}}
						/>
						<div className="other-options">
							<CheckBox
								width={63}
								disabled={state.simpleCascade !== 1}
								checked={state.cascadeUpload}
								onChange={(e, v) => {
									update({ cascadeUpload: v })
								}}
							>
								{t('上传')}
							</CheckBox>
							<CheckBox
								className="multi-uploading-checkbox__i18n"
								width={63}
								disabled={state.simpleCascade !== 1}
								checked={state.cascadeReturn}
								onChange={(e, v) => {
									update({ cascadeReturn: v, cascadeReturnPara: '' })
								}}
							>
								{t('回传')}
							</CheckBox>
							{state.cascadeReturn && (
								<>
									<span className={`text ${state.simpleCascade !== 1 ? 'disabled' : ''}`}>
										{t('带宽')}
									</span>
									<InputNumber
										className="cascade-input"
										placeholder={t('请输入')}
										focusMsg={t('回传带宽范围为：1M~1000M')}
										width={40}
										disabled={state.simpleCascade !== 1}
										rule={getRule('cascadeReturnPara')}
										value={state.cascadeReturnPara}
										onChange={(e, v) => {
											update({ cascadeReturnPara: v })
										}}
									/>
									<span className={`text ${state.simpleCascade !== 1 ? 'disabled' : ''}`}>Mbps</span>
									<CheckBox
										disabled={state.simpleCascade !== 1}
										className="multi-checkbox"
										checked={state.multiStream}
										onChange={(e, v) => {
											update({ multiStream: v })
										}}
									>
										{t('多流')}
									</CheckBox>
								</>
							)}
						</div>
					</>
				)}
			</LabelWrap>
			<LabelWrap label={t('初始哑音')}>
				<Switch
					width={40}
					height={22}
					checked={state.initMute}
					onChange={(e, v) => {
						update({ initMute: v })
					}}
					className="switch"
				></Switch>
			</LabelWrap>
			<LabelWrap label={t('全场哑音例外')}>
				<Switch
					width={40}
					height={22}
					checked={state.muteException}
					onChange={(e, v) => {
						update({ muteException: v })
					}}
					className="switch"
				></Switch>
				<span className="tip">{t('开启后，全场哑音操作对发言方管理方不生效')}</span>
			</LabelWrap>
			<LabelWrap label={t('纯转发会议')} show={state.meetingType === 0 && !permission.integrated}>
				<Switch
					width={40}
					height={22}
					checked={state.sourceUsed === 2}
					disabled={isSourceUsedDisabled}
					className="switch"
					onChange={(e, v) => {
						if (
							v &&
							state.enableRtc &&
							state.meetingType === 0 &&
							permission.tradMix !== 0 &&
							!permission.integrated
						) {
							Alert(t('传统会议纯转发会议不支持RTC接入'))
							return
						}
						if (useBasicInfoStore.getState().superMtNum) {
							Alert(t('传统会议纯转发会议不支持超大方。'))
							return false
						}
						update({ sourceUsed: v ? 2 : 0 })
					}}
				/>
				<div className="tip">{t('开启后，仅支持召开传统纯转发类型的会议。')}</div>
			</LabelWrap>
			<LabelWrap
				label={t('资源预占')}
				show={state.meetingType === 0 && !permission.integrated && state.sourceUsed !== 2}
			>
				<Switch
					width={40}
					height={22}
					disabled={isSourceUsedDisabled}
					checked={Boolean(state.sourceUsed)}
					onChange={(e, v) => {
						update({ sourceUsed: v ? 1 : 0 })
					}}
					className="switch"
				/>
				<div className="tip">{t('开启后，会议始终占用资源直至会议结束')}</div>
			</LabelWrap>
			<LabelWrap label={t('会议免打扰')}>
				<Switch
					width={40}
					height={22}
					checked={state.closedMeeting}
					onChange={(e, v) => {
						update({ closedMeeting: v })
					}}
					className="switch"
				></Switch>
				<span className="tip">{t('开启后，所有会场不可主动加入会议，必须由会议邀请会场。')}</span>
			</LabelWrap>
			<LabelWrap label={t('会议不可见')}>
				<Switch
					width={40}
					height={22}
					checked={state.meetingSafe}
					onChange={(e, v) => {
						update({ meetingSafe: v })
					}}
					className="switch"
				></Switch>
				<span className="tip">
					{t('开启后，所有会场不可主动加入会议，必须由会议邀请会场，且仅受邀列表成员可见。')}
				</span>
			</LabelWrap>
			<LabelWrap label={t('视频会议水印')}>
				<Switch
					width={40}
					height={22}
					checked={state.watermark}
					onChange={(e, v) => {
						update({ watermark: v })
					}}
				></Switch>
			</LabelWrap>
			<LabelWrap label={t('会议密码')}>
				<Input
					className="conference-password-input"
					width={210}
					placeholder={t('请设定密码')}
					focusMsg={t('可输入16个字符，仅限数字')}
					maxLength={16}
					rule={getRule('password')}
					value={state.password}
					canCopy={false}
					onChange={(e, v) => {
						update({ password: v })
					}}
				/>
			</LabelWrap>
			<LabelWrap
				label={t('匿名用户登录')}
				show={(state.enableRtc || (!state.enableRtc && state.meetingType === 2)) && !state._H265}
			>
				<CheckBox
					width={180}
					checked={state.allowAnonymousMt}
					onChange={(e, v) => {
						update({ allowAnonymousMt: v })
					}}
				>
					{t('允许')}
				</CheckBox>
			</LabelWrap>
			<LabelWrap label={t('数据加密')} className="encryption-line" show={!isSfu}>
				<Select
					container={() => _container}
					value={state.encryptionType}
					options={encryptionTypeSourceList}
					onChange={(e, v) => {
						changeEncryptionType(v)
					}}
				/>
				{state.encryptionType === 2 && (
					<Input
						width={210}
						placeholder={t('可输入数据加密密码')}
						focusMsg={t('可输入16个字符，包括英文字母(大小写)、数字、"."、"_"')}
						maxLength={16}
						style={{ marginLeft: 50 }}
						rule={getRule('encryptedKey')}
						value={state.encryptedKey}
						onChange={(e, v) => {
							update({ encryptedKey: v })
						}}
					/>
				)}
				{state.encryptionType === 3 && permission.enableQuantum && (
					<CheckBox
						style={{ marginLeft: 30 }}
						checked={state.quantumEncryption}
						onChange={(e, v) => {
							update({ quantumEncryption: v })
						}}
					>
						{t('量通加密')}
					</CheckBox>
				)}
				{state.encryptionType === 3 && (
					<div className="certificate-options">
						{permission.sm1 && (
							<CheckBox
								width={295}
								checked={state.encryptedSM}
								onChange={(e, v) => {
									update({ encryptedSM: v })
								}}
							>
								{t('只允许硬件终端加入国密会议(使用SM1算法)')}
							</CheckBox>
						)}
						<CheckBox
							checked={state.encryptedAuth}
							onChange={(e, v) => {
								if (v && !permission.hasAuthenticationServer) {
									Alert(t('尚未配置动态口令服务器，不可勾选“启用终端强认证”'))
									return
								}
								const meetingMoid = useCreateContentStore.getState().meetingMoid
								//编辑状态取消勾选强认证
								if (meetingMoid && !v) {
									checkAuthentication(meetingMoid, (flag) => {
										if (flag) {
											update({ encryptedAuth: v })
										}
									})
								} else {
									update({ encryptedAuth: v })
								}
							}}
						>
							{t('启用终端强认证')}
						</CheckBox>
					</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('内容共享')} className="double-flow-wrap double-flow__i18n">
				<RadioGroup
					direction="column"
					value={state.doubleFlowLimit}
					options={[
						{ label: t('发言会场'), value: 0, className: 'first-radio-item' },
						{ label: t('任意会场'), value: 1 },
					]}
					onChange={(e, v) => {
						update({ doubleFlowLimit: v, sendDoubleFlowAtOnce: false })
					}}
				/>
				<CheckBox
					className="once-checkbox"
					disabled={state.doubleFlowLimit === 1}
					checked={state.sendDoubleFlowAtOnce}
					onChange={(e, v) => {
						update({ sendDoubleFlowAtOnce: v })
					}}
				>
					{t('会议开启立即发送内容共享（仅部分终端支持）')}
				</CheckBox>
			</LabelWrap>
			<LabelWrap label={t('视频质量')} show={!isSfu} className="video_quality__i18n">
				<RadioGroup
					value={state.videoQuality}
					options={[
						{ label: t('质量优先'), value: 0, width: 122 },
						{ label: t('速度优先'), value: 1, width: 122 },
					]}
					onChange={(e, v) => {
						update({ videoQuality: v })
					}}
				/>
			</LabelWrap>
			<LabelWrap label={t('呼叫方式')} show={!isSfu} className="call_type">
				<RadioGroup
					direction="column"
					value={state.callMode}
					options={[
						{ label: t('自动呼叫'), value: 2, className: 'first-radio-item' },
						{ label: t('手动呼叫'), value: 0 },
					]}
					onChange={(e, val) => {
						update({
							callMode: val,
							callInterval: '20',
							callTimes: '',
							callTimesUnlimited: val === 2 ? true : false,
						})
					}}
				></RadioGroup>
				<div className="auto-call-options">
					<span>{t('呼叫间隔')}</span>
					<InputNumber
						className="call-input"
						disabled={state.callMode === 0}
						focusMsg={t('呼叫间隔为10~300秒')}
						width={45}
						maxLength={16}
						rule={getRule('callInterval')}
						value={state.callInterval}
						onChange={(e, v) => {
							update({ callInterval: v })
						}}
					/>
					<span style={{ color: state.callMode === 0 ? '#b6b6b6' : '#4e4e4e' }}>{t('10-300秒')}</span>
					<span style={{ marginLeft: 7, color: state.callMode === 0 ? '#b6b6b6' : '#4e4e4e' }}>
						{t('呼叫次数')}
					</span>
					<InputNumber
						className="call-input"
						disabled={state.callMode === 0 || state.callTimesUnlimited}
						focusMsg={t('呼叫次数为2~99秒')}
						width={45}
						maxLength={16}
						rule={getRule('callTimes')}
						value={state.callTimes}
						onChange={(e, v) => {
							update({ callTimes: v })
						}}
					/>
					<span style={{ color: state.callMode === 0 || state.callTimesUnlimited ? '#b6b6b6' : '#4e4e4e' }}>
						{t('2-99次')}
					</span>
					<CheckBox
						style={{ marginLeft: 30 }}
						checked={state.callTimesUnlimited}
						disabled={state.callMode === 0}
						onChange={(e, v) => {
							update({ callTimesUnlimited: v, callTimes: '' })
						}}
					>
						{t('不限次数')}
					</CheckBox>
				</div>
			</LabelWrap>
			<LabelWrap label={t('追呼设置')} show={!isSfu} className="keep-call-wrap">
				<CreateMember
					list={state.keep_calling_members}
					setOuterList={(h, type) => {
						if (type === 'drop') {
							setKcList(h)
						} else {
							update({ keep_calling_members: h })
						}
					}}
				></CreateMember>
			</LabelWrap>
			<LabelWrap label={t('语音激励')} show={!isSfu} className="voice-inspire-wrap">
				<Switch
					width={40}
					height={22}
					checked={state.voiceInspireEnable}
					onChange={(e, v) => {
						changeVoiceInspireEnable(v, true)
					}}
				/>
				{state.voiceInspireEnable && (
					<Select
						container={() => _container}
						style={{ marginLeft: 30 }}
						value={state.voiceInspireTime}
						options={[
							{ label: '3s', value: 3 },
							{ label: '5s', value: 5 },
							{ label: '15s', value: 15 },
							{ label: '30s', value: 30 },
						]}
						onChange={(e, v) => {
							update({ voiceInspireTime: v })
						}}
					/>
				)}
			</LabelWrap>
			<LabelWrap label={t('归一重整')} show={!isSfu}>
				<Switch
					width={40}
					height={22}
					checked={state.oneReforming}
					onChange={(e, v) => {
						update({ oneReforming: v })
					}}
				></Switch>
			</LabelWrap>
			<LabelWrap label="FEC" show={!isSfu}>
				<Switch
					width={40}
					height={22}
					checked={state.fecMode}
					onChange={(e, v) => {
						update({ fecMode: v })
					}}
				></Switch>
			</LabelWrap>
			<AuthenticationCheck open={isAuthenticationOpen} setOpen={setIsAuthenticationOpen} callBack={successFn} />
		</StyledWrap>
	)
}
